package com.starblink.mine.personhome.ui.follow.ui.followlist.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.SearchAccountsQuery
import com.starblink.rocketreserver.SearchAccountsQuery.SearchAccount
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class FollowListVM : BaseViewModel() {
    var accountId: String = ""
    var searchScope: Int = 0
    var curPageNo = 0 // 当前列表页数，默认是0
    private val listResponse: ListResponse = ListResponse()

    // 普通列表数据
    val listResponseLiveData: MutableLiveData<ListResponse> =
        MutableLiveData()

    var searchContent: String? = null
    var curSearchPageNo = 0 // 当前搜索列表页数，默认是0
    private val searchListResponse: ListResponse = ListResponse()

    // 搜索列表数据
    var searchListResponseLiveData: MutableLiveData<ListResponse> =
        MutableLiveData()

    // 显示或隐藏搜索结果页面
    val showSearchResultLiveData: MutableLiveData<Boolean> =
        MutableLiveData()

    /**
     * 保存服务器返回数据
     */
    inner class ListResponse {
        val totalList = ArrayList<SearchAccount>() // 保存全部列表数据
        lateinit var pageList: List<SearchAccount> // 保存单页请求数据
        var refresh: Boolean = true // true-下拉刷新，false表示加载更多
    }

    /**
     * 获取关注列表 或者 粉丝列表
     * @param refresh: true表示请求首页，false表示请求下一页
     */
    fun getFollowList(refresh: Boolean = true) {
        val requestPageNo = if (refresh) 1 else curPageNo + 1
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                /**
                 * @param searchScope：查询范围:0-全部,1-关注,2-粉丝
                 * searchScope!=0时，accountId必传, 表示查看谁的粉丝、谁的关注。
                 * @param content：搜索内容
                 */
                SearchAccountsQuery(
                    searchScope = Optional.present(searchScope),
                    accountId = Optional.present(accountId),
                    pageNo = requestPageNo,
                    pageSize = Optional.present(PAGE_SIZE)
                )
            )
            if (response?.data != null && response.data!!.searchAccounts != null) {
                curPageNo = requestPageNo
                listResponse.apply {
                    pageList = response.data!!.searchAccounts!!
                    this.refresh = refresh

                    if (refresh) {
                        totalList.clear()
                    }
                    totalList.addAll(pageList)
                }
                listResponseLiveData.postValue(listResponse)
            } else {
                // 加载失败，提示用户（已toast提示）
                loadError(null)
            }
        }
    }

    /**
     * 获取搜索关注列表 或者 搜索粉丝列表
     * @param refresh: true表示请求首页，false表示请求下一页
     */
    fun getSearchFollowList(refresh: Boolean = true) {
        val requestPageNo = if (refresh) 1 else curSearchPageNo + 1
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                SearchAccountsQuery(
                    searchScope = Optional.present(searchScope),
                    accountId = Optional.present(accountId),
                    content = Optional.presentIfNotNull(searchContent),
                    pageNo = requestPageNo,
                    pageSize = Optional.present(PAGE_SIZE)
                )
            )
            if (response?.data != null && response.data!!.searchAccounts != null) {
                curSearchPageNo = requestPageNo
                searchListResponse.apply {
                    pageList = response.data!!.searchAccounts!!
                    this.refresh = refresh

                    if (refresh) {
                        totalList.clear()
                    }
                    totalList.addAll(pageList)
                }
                searchListResponseLiveData.postValue(searchListResponse)
            } else {
                // 加载失败，提示用户（已toast提示）
                loadError(null)
            }
        }
    }

    fun searchFollowListFlow(key: String) = flow {
        if (key.isNotEmpty()) {
            var searchResult: List<SearchAccount>?
            try {
                searchResult = searchFollowList(key)
//                YYLogUtils.e("after searchFollowList $key", "dss")
            } catch (e: Exception) {
                YYLogUtils.e("$e for key=$key", "dss")
                return@flow
            }
            searchResult?.let { emit(it) }
        } else {
            // 搜索关键字为空，隐藏搜索结果视图
            showSearchResultLiveData.postValue(false)
            searchContent = ""
        }
    }

    /**
     * 获取搜索关注列表 或者 搜索粉丝列表
     */
    suspend fun searchFollowList(key: String): List<SearchAccount>? {
        YYLogUtils.e("searchFollowList $key in thread${Thread.currentThread().name}", "dss")
        val requestPageNo = 1
        val response = SkGqlClient.skQuery(
            SearchAccountsQuery(
                searchScope = Optional.present(searchScope),
                accountId = Optional.present(accountId),
                content = Optional.present(key),
                pageNo = requestPageNo,
                pageSize = Optional.present(PAGE_SIZE)
            )
        )
        if (response?.data != null && response.data!!.searchAccounts != null) {
            // 成功获取搜索结果，显示出来
            curSearchPageNo = requestPageNo
            searchContent = key
            showSearchResultLiveData.postValue(true)
            searchListResponse.apply {
                pageList = response.data!!.searchAccounts!!
                this.refresh = true

                if (refresh) {
                    totalList.clear()
                }
                totalList.addAll(pageList)
            }
            searchListResponseLiveData = MutableLiveData(searchListResponse)
            return response.data!!.searchAccounts!!
        }
        return null
    }

    companion object {
        const val PAGE_SIZE = 20
    }
}